import { memo, useState, useCallback, useRef, useEffect } from "react"
import styled from "@emotion/styled"
import Svg from "@/components/base/Svg"
import { Controller, Control } from "react-hook-form"
import { Props } from "@/components/form_item/formItemConfig"

const DatePickerStyled = styled.div`
    padding: 8rem 10rem;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 8rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14rem;
    color: #40444f;
    cursor: pointer;
`

const DatePicherTextStyled = styled.span`
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
`

const DatePickerIcon = styled.div`
    width: 12.67rem;
    height: 15.08rem;

    img {
        width: 100%;
        height: 100%;
        object-fit: contain;
    }
`

const DatePickerModal = styled.div<{ isOpen: boolean }>`
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: ${(props) => (props.isOpen ? "flex" : "none")};
    justify-content: center;
    align-items: flex-end;
    z-index: 1000;
`

const DatePickerContent = styled.div<{ isOpen: boolean }>`
    border-radius: 16rem 16rem 0 0;
    width: 100%;
    max-width: 375rem;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background:
        linear-gradient(0deg, rgba(255, 255, 255, 0.96), rgba(255, 255, 255, 0.96)),
        radial-gradient(
            49.86% 72.92% at 0% 0%,
            rgba(255, 71, 120, 0.1) 0%,
            rgba(255, 71, 120, 0) 100%
        );

    animation: ${(props) =>
        props.isOpen ? "slideDown 0.3s ease forwards" : "slideUp 0.3s ease forwards"};
    @keyframes slideDown {
        from {
            transform: translateY(100%);
        }
        to {
            transform: translateY(0);
        }
    }
    @keyframes slideUp {
        from {
            transform: translateY(0);
        }
        to {
            transform: translateY(100%);
        }
    }
`

const DatePickerHeader = styled.div`
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10rem 20rem;
    position: relative;
`

const DatePickerTitle = styled.h2`
    margin: 0;
    font-family: Gilroy;
    font-weight: 500;
    font-size: 16rem;
    text-align: center;
    text-transform: capitalize;
`

const CloseButton = styled.button`
    background: none;
    border: none;
    font-size: 24rem;
    cursor: pointer;
    padding: 0;
    color: #333;
    width: 14rem;
    height: 14rem;
    display: flex;
    align-items: center;
    position: absolute;
    right: 20rem;
    top: 50%;
    transform: translateY(-50%);

    img {
        width: 100%;
        height: 100%;
        object-fit: contain;
    }
`

const WeekDaysRow = styled.div`
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    text-align: center;
    padding: 8rem 0 12rem 0;
    border-bottom: 1px solid #1c1e2126;
`

const WeekDay = styled.div<{ isWeekend?: boolean }>`
    font-size: 14rem;
    color: ${(props) => (props.isWeekend ? "#FF356B" : "#40444F")};
    font-family: Gilroy;
    font-weight: 400;
    text-align: center;
`

const MonthTitle = styled.div`
    text-align: center;
    font-size: 18rem;
    font-weight: 500;
    padding: 10rem 0;

    font-family: Gilroy;
    color: #131416;
    text-transform: capitalize;
`

const DaysGrid = styled.div`
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 5rem 0;
    padding: 10rem;
`

const DayCell = styled.div<{
    isSelected?: boolean
    isInRange?: boolean
    isRangeStart?: boolean
    isRangeEnd?: boolean
    isWeekend?: boolean
    isCurrentMonth?: boolean
    isToday?: boolean
}>`
    height: 28rem;
    font-family: Gilroy;
    font-weight: 400;
    font-size: 14rem;
    text-align: center;
    color: #9fa7bc;

    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: ${(props) =>
        props.isRangeStart
            ? "14rem 0 0 14rem"
            : props.isRangeEnd
              ? "0 14rem 14rem 0"
              : props.isSelected
                ? "28rem"
                : "0"};
    background-color: ${(props) =>
        props.isSelected
            ? "#F51450"
            : props.isInRange
              ? "rgba(255, 53, 107, 0.15)"
              : "transparent"};
    color: ${(props) => (props.isSelected ? "#fff" : props.isInRange ? "#F51450" : "#40444F")};
    cursor: pointer;
    position: relative;
    visibility: ${(props) => (props.isCurrentMonth ? "visible" : "hidden")};

    // 使用 ::after 伪元素为今天的日期添加红色圆圈，设置固定宽高并居中
    ${(props) =>
        props.isToday && !props.isSelected
            ? `
        &::after {
            content: "";
            position: absolute;
            width: 28rem;
            height: 28rem;
            border: 1px solid #F51450;
            border-radius: 50%;
            pointer-events: none;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    `
            : ""}

    &:hover {
        background-color: ${(props) =>
            props.isSelected
                ? "#F51450"
                : props.isInRange
                  ? "rgba(255, 77, 109, 0.3)"
                  : "rgba(0, 0, 0, 0.05)"};
    }
`

const MonthSelector = styled.div`
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    max-height: 386rem;
    scroll-behavior: smooth;
    border-bottom: 1px solid #1c1e2126;
`

const ConfirmButton = styled.button`
    background: linear-gradient(90deg, #ff3568 10%, #ff33cc 100%);
    color: white;
    border: none;
    border-radius: 6rem;
    padding: 15rem 0;
    margin: 15rem;
    font-size: 16rem;
    font-weight: 500;
    cursor: pointer;

    &:hover {
        background: #ff3d5d;
    }
`

interface ComponentProps {
    style?: React.CSSProperties
    onChange?: (range: { startDate: Date; endDate: Date }) => void
    initValue?: { startDate: Date; endDate: Date }
    className?: string
}

const Component: React.FC<React.PropsWithChildren<ComponentProps>> = (props) => {
    const [isOpen, setIsOpen] = useState(false)
    const [currentMonth, setCurrentMonth] = useState(new Date())
    const [startDate, setStartDate] = useState<Date | null>(null)
    const [endDate, setEndDate] = useState<Date | null>(null)
    const [displayRange, setDisplayRange] = useState("Select date range")

    const monthSelectorRef = useRef<HTMLDivElement>(null)

    // 添加新的 useEffect 钩子，在日期选择器打开时滚动到当前月份
    useEffect(() => {
        if (isOpen && monthSelectorRef.current) {
            const currentMonthIndex = new Date().getMonth()
            const monthElements = monthSelectorRef.current.children
            if (monthElements[currentMonthIndex]) {
                monthElements[currentMonthIndex].scrollIntoView({ behavior: "auto" })
            }
        }
    }, [isOpen])

    // 生成月份数据
    const generateMonthData = useCallback((date: Date) => {
        const year = date.getFullYear()
        const month = date.getMonth()
        const firstDay = new Date(year, month, 1)
        const lastDay = new Date(year, month + 1, 0)

        const daysInMonth = lastDay.getDate()
        const startDayOfWeek = firstDay.getDay()

        // 上个月的最后几天
        const prevMonthLastDay = new Date(year, month, 0).getDate()
        const prevMonthDays = Array.from({ length: startDayOfWeek }, (_, i) => ({
            day: prevMonthLastDay - startDayOfWeek + i + 1,
            isCurrentMonth: false,
            date: new Date(year, month - 1, prevMonthLastDay - startDayOfWeek + i + 1),
        }))

        // 当前月的天数
        const currentMonthDays = Array.from({ length: daysInMonth }, (_, i) => ({
            day: i + 1,
            isCurrentMonth: true,
            date: new Date(year, month, i + 1),
        }))

        // 下个月的前几天
        const nextMonthDays = Array.from(
            { length: 42 - (prevMonthDays.length + currentMonthDays.length) },
            (_, i) => ({
                day: i + 1,
                isCurrentMonth: false,
                date: new Date(year, month + 1, i + 1),
            }),
        )

        return [...prevMonthDays, ...currentMonthDays, ...nextMonthDays]
    }, [])

    // 检查日期是否在选择范围内
    const isDateInRange = useCallback(
        (date: Date) => {
            if (!startDate || !endDate) return false
            return date >= startDate && date <= endDate
        },
        [startDate, endDate],
    )

    // 检查日期是否是范围的开始或结束
    const isRangeStart = useCallback(
        (date: Date) => {
            if (!startDate) return false
            return (
                date.getDate() === startDate.getDate() &&
                date.getMonth() === startDate.getMonth() &&
                date.getFullYear() === startDate.getFullYear()
            )
        },
        [startDate],
    )

    const isRangeEnd = useCallback(
        (date: Date) => {
            if (!endDate) return false
            return (
                date.getDate() === endDate.getDate() &&
                date.getMonth() === endDate.getMonth() &&
                date.getFullYear() === endDate.getFullYear()
            )
        },
        [endDate],
    )

    // 处理日期选择
    const handleDateClick = useCallback(
        (date: Date) => {
            if (!startDate || (startDate && endDate)) {
                setStartDate(date)
                setEndDate(null)
            } else {
                if (date < startDate) {
                    setEndDate(startDate)
                    setStartDate(date)
                } else {
                    setEndDate(date)
                }
            }
        },
        [startDate, endDate],
    )

    // 格式化日期显示
    const formatDate = useCallback((date: Date) => {
        return date.toLocaleDateString("en-US", {
            month: "2-digit",
            day: "2-digit",
            year: "numeric",
        })
    }, [])

    // 确认选择
    const handleConfirm = useCallback(() => {
        if (startDate && endDate) {
            const formattedRange = `${formatDate(startDate)} - ${formatDate(endDate)}`
            setDisplayRange(formattedRange)
            if (props.onChange) {
                props.onChange({ startDate, endDate })
            }
        } else if (startDate) {
            const formattedDate = formatDate(startDate)
            setDisplayRange(formattedDate)
            if (props.onChange) {
                props.onChange({ startDate, endDate: startDate })
            }
        }
        setIsOpen(false)
    }, [startDate, endDate, formatDate, props.onChange])

    // 生成月份选择器
    const renderMonths = useCallback(() => {
        const today = new Date()
        const currentYear = today.getFullYear()

        // 生成12个月
        return Array.from({ length: 12 }, (_, i) => {
            const monthDate = new Date(currentYear, i, 1)
            const monthName = monthDate.toLocaleString("en-US", { month: "long" })?.substring(0, 3)
            const year = monthDate.getFullYear()

            return (
                <div key={`${year}-${i}`}>
                    <MonthTitle>{`${monthName} ${year}`}</MonthTitle>
                    <DaysGrid>
                        {generateMonthData(monthDate).map((day, index) => {
                            const isWeekend = index % 7 === 0 || index % 7 === 6
                            const isSelected = isRangeStart(day.date) || isRangeEnd(day.date)
                            const inRange = isDateInRange(day.date)

                            // 判断是否是今天
                            const isToday =
                                day.date.getDate() === today.getDate() &&
                                day.date.getMonth() === today.getMonth() &&
                                day.date.getFullYear() === today.getFullYear()

                            return (
                                <DayCell
                                    key={index}
                                    isSelected={isSelected}
                                    isInRange={inRange}
                                    isRangeStart={isRangeStart(day.date)}
                                    isRangeEnd={isRangeEnd(day.date)}
                                    isWeekend={isWeekend}
                                    isCurrentMonth={day.isCurrentMonth}
                                    isToday={isToday}
                                    onClick={() => handleDateClick(day.date)}
                                >
                                    {day.day}
                                </DayCell>
                            )
                        })}
                    </DaysGrid>
                </div>
            )
        })
    }, [generateMonthData, isDateInRange, isRangeStart, isRangeEnd, handleDateClick])

    // 初始化日期
    useEffect(() => {
        // 不再默认选中今天
        setDisplayRange("Select date range")
        // 清空选择的日期
        setStartDate(null)
        setEndDate(null)
    }, [formatDate])

    return (
        <>
            <DatePickerStyled
                style={props.style}
                className={props.className}
                onClick={() => setIsOpen(true)}
            >
                <DatePicherTextStyled>{displayRange}</DatePicherTextStyled>
                <DatePickerIcon>
                    <Svg src="pages/TransactionRecordPage/images/subtract.svg" />
                </DatePickerIcon>
            </DatePickerStyled>

            <DatePickerModal isOpen={isOpen}>
                <DatePickerContent isOpen={isOpen}>
                    <DatePickerHeader>
                        <DatePickerTitle>Choose Date</DatePickerTitle>
                        <CloseButton onClick={() => setIsOpen(false)}>
                            <Svg src="base_image/cancel_noBg.svg" />
                        </CloseButton>
                    </DatePickerHeader>

                    <WeekDaysRow>
                        <WeekDay isWeekend>Sun</WeekDay>
                        <WeekDay>Mon</WeekDay>
                        <WeekDay>Tue</WeekDay>
                        <WeekDay>Wed</WeekDay>
                        <WeekDay>Thu</WeekDay>
                        <WeekDay>Fri</WeekDay>
                        <WeekDay isWeekend>Sat</WeekDay>
                    </WeekDaysRow>

                    <MonthSelector ref={monthSelectorRef}>{renderMonths()}</MonthSelector>

                    <ConfirmButton onClick={handleConfirm}>Confirm</ConfirmButton>
                </DatePickerContent>
            </DatePickerModal>
        </>
    )
}

const DatePicker = memo(Component)

type FormValues = {
    range: { startDate: Date; endDate: Date }
}

type DateProps = Props & {
    control: Control
    initValue?: { startDate: Date; endDate: Date }
}
export const ReactHookFormDatePicker = ({
    fieldName,
    onClick,
    control,
    initValue,
    className = "",
    style,
}: DateProps) => {
    return (
        <Controller
            name={fieldName}
            control={control}
            render={({ field: { onChange, onBlur, value }, formState, fieldState }) => {
                return (
                    <DatePicker
                        style={style}
                        className={className}
                        initValue={initValue}
                        onChange={(e) => {
                            if (onChange) {
                                onChange(e)
                            }
                            if (onClick) {
                                onClick()
                            }
                        }}
                    />
                )
            }}
        />
    )
}

export default DatePicker
